package com.sunseen.capacitormachine.modules.parameter.productparameter.edit;

import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.widget.EditText;
import android.widget.Toast;

import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.format.selected.BaseSelectFormat;
import com.bin.david.form.data.table.FormTableData;
import com.bin.david.form.data.table.TableData;
import com.sunseen.capacitormachine.R;
import com.sunseen.capacitormachine.common.Form;
import com.sunseen.capacitormachine.databinding.FragmentEditSprayCodeBinding;
import com.sunseen.capacitormachine.common.BaseFragment;
import com.sunseen.capacitormachine.modules.parameter.productivetask.event.SetParameterEvent;

import androidx.databinding.ViewDataBinding;

import org.greenrobot.eventbus.EventBus;

/**
 * @author zest
 */
public class EditSprayCodeFragment extends BaseFragment {

    private Form selectForm;
    private int curCol = -1;
    private int curRow = -1;
    private TextWatcher textWatcher1;
    private TextWatcher textWatcher2;

    @Override
    protected int setLayout() {
        return R.layout.fragment_edit_spray_code;
    }

    @Override
    protected void onBindView(ViewDataBinding viewDataBinding) {

        final FragmentEditSprayCodeBinding binding = (FragmentEditSprayCodeBinding) viewDataBinding;
        editText = binding.editInput;
        textWatcher1 = new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = s.toString();
                if (str.contains(".")) {
                    int pointIndex = str.indexOf(".");
                    if (str.length() - pointIndex > 2) {
                        binding.editInput.setText(str.substring(0, pointIndex + 2));
                    }
                }
            }
        };

        textWatcher2 = new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = s.toString();
                if (str.contains(".")) {
                    int pointIndex = str.indexOf(".");
                    if (str.length() - pointIndex > 3) {
                        binding.editInput.setText(str.substring(0, pointIndex + 3));
                    }
                }
            }
        };
        Form[][] forms = new Form[][]{
                {new Form(getString(R.string.prefix_mark)), new Form("", 10)},
                {new Form(getString(R.string.start_number)), new Form("", 10)},
                {new Form(getString(R.string.implosion_current_up_limit)), new Form(getString(R.string.ua), 10)},
                {new Form(getString(R.string.implosion_current_low_limit)), new Form(getString(R.string.ua), 10)},
                {new Form(getString(R.string.implosion_voltage_up_limit)), new Form(getString(R.string.volt), 10)},
                {new Form(getString(R.string.implosion_voltage_low_limit)), new Form(getString(R.string.volt), 10)},
                {new Form(getString(R.string.implosion_duration)), new Form(getString(R.string.ms), 10)}
        };

        FormTableData<Form> tableData = FormTableData.create(binding.table, "", 11, forms);
        tableData.setFormat((t) -> {
            if (t != null) {
                return t.getContent();
            } else {
                return "";
            }
        });
        tableData.setOnItemClickListener(new TableData.OnItemClickListener<Form>() {
            @Override
            public void onClick(Column column, String value, Form form, int col, int row) {
                curCol = col;
                curRow = row;
                if (col == 1) {
                    selectForm = form;
                    binding.editInput.setText("");
                    binding.btnInput.setEnabled(true);
                    switch (row) {
                        case 0: {
                            binding.editInput.setInputType(InputType.TYPE_CLASS_TEXT);
                        }
                        break;
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5: {
                            removeAllListener();
                            binding.editInput.setKeyListener(new DigitsKeyListener(false, false));
                        }
                        break;
                        case 6: {
                            removeAllListener();
                            binding.editInput.setKeyListener(new DigitsKeyListener(false, true));
                            binding.editInput.addTextChangedListener(textWatcher2);
                        }
                        break;
                    }
                } else {
                    binding.btnInput.setEnabled(false);
                }
            }
        });
        binding.table.getConfig().setShowXSequence(false);
        binding.table.getConfig().setShowYSequence(false);
        binding.table.getConfig().setShowTableTitle(false);
        binding.table.getConfig().getContentGridStyle()
                .setColor(getResources().getColor(R.color.table_content_grid_color));
        binding.table.getConfig().getContentStyle()
                .setTextColor(getResources().getColor(R.color.table_content_text_color));
        binding.table.setSelectFormat(new BaseSelectFormat());
        binding.table.setTableData(tableData);
        binding.btnInput.setOnClickListener((view) -> {
            if (curCol == 1) {
                String content = binding.editInput.getText().toString();
                //用户未输入，或只输入了一个小数点，不做处理，提示用户输入错误
                if (content.length() == 0 || (content.length() == 1 && ".".equals(content))) {
                    Toast.makeText(_mActivity, getString(R.string.number_input_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                switch (curRow) {
                    case 0: {
                        if (content.length() == 8) {
                            byte[] bytes = content.getBytes();
                            if (isLetter(bytes[0]) && isLetter(bytes[1])
                                    && isNumber(bytes[2]) && isNumber(bytes[3])
                                    && isNumber(bytes[4]) && isNumber(bytes[5])
                                    && isNumber(bytes[4]) && isNumber(bytes[5])
                                    && isNumber(bytes[6]) && isNumber(bytes[7])
                            ) {
                                selectForm.setContent(content);
                                binding.table.invalidate();
                                EventBus.getDefault().post(new SetParameterEvent(true, "codingMark", content));
                            } else {
                                Toast.makeText(_mActivity, getString(R.string.coding_remark_tip),
                                        Toast.LENGTH_SHORT).show();
                            }
                        } else {

                            Toast.makeText(_mActivity, getString(R.string.coding_remark_tip),
                                    Toast.LENGTH_SHORT).show();
                        }

                    }
                    break;
                    case 1: {
                        if (content.length() > 8) {
                            Toast.makeText(_mActivity, "起始编号长度不能大于8", Toast.LENGTH_SHORT).show();
                        } else {
                            char[] zeroIntChars = new char[8];
                            for (int i = 0; i < 8 - content.length(); i++) {
                                zeroIntChars[i] = '0';
                            }
                            char[] contentChars = content.toCharArray();
                            for (int i = 8 - content.length(), j = 0; i < 8; i++, j++) {
                                zeroIntChars[i] = contentChars[j];
                            }
                            String zeroStartString = new String(zeroIntChars);
                            selectForm.setContent(zeroStartString);
                            binding.table.invalidate();
                            EventBus.getDefault().post(new SetParameterEvent(true, "codingStartNumber", zeroStartString));
                        }
                    }
                    break;
                    case 2: {
                        selectForm.setContent(content + getString(R.string.ua));
                        binding.table.invalidate();
                        EventBus.getDefault().post(new SetParameterEvent(true, "implosionCurrentUpperLimit", content));
                    }
                    break;
                    case 3: {
                        selectForm.setContent(content + getString(R.string.ua));
                        binding.table.invalidate();
                        EventBus.getDefault().post(new SetParameterEvent(true, "implosionCurrentLowerLimit", content));

                    }
                    break;
                    case 4: {
                        selectForm.setContent(content + getString(R.string.volt));
                        binding.table.invalidate();
                        EventBus.getDefault().post(new SetParameterEvent(true, "implosionVoltageUpperLimit", content));
                    }
                    break;
                    case 5: {
                        selectForm.setContent(content + getString(R.string.volt));
                        binding.table.invalidate();
                        EventBus.getDefault().post(new SetParameterEvent(true, "implosionVoltageLowerLimit", content));
                    }
                    break;
                    case 6: {
//                        int value = (int) (Float.valueOf(content) * 100);
//                        if (value % 2 == 0) {
                        selectForm.setContent(content + getString(R.string.ms));
                        binding.table.invalidate();
                        EventBus.getDefault().post(new SetParameterEvent(true, "implosionTime", content));
//                        } else {
//                            Toast.makeText(_mActivity, R.string.implosion_time_tip, Toast.LENGTH_SHORT).show();
//                        }

                    }
                    break;
                }
            }
        });
    }

    private EditText editText;

    private void removeAllListener() {
        if (editText != null) {
            editText.removeTextChangedListener(textWatcher1);
            editText.removeTextChangedListener(textWatcher2);
        }
    }

    private boolean isLetter(byte b) {
        int i = b & 0xFF;
        return (i >= 65 && i <= 90) || (i >= 97 && i <= 122);
    }

    private boolean isNumber(byte b) {
        int i = b & 0xFF;
        return i >= 48 && i <= 57;
    }
}
